//
//  YYMDownloadViewController.m
//  On The Load
//
//  Created by 我爱的妞 on 15/11/18.
//  Copyright © 2015年 @@叶一闽. All rights reserved.
//

#import "YYMDownloadViewController.h"
#import "XJCVideoPlayViewController.h"
#import "XJCVideoModel.h"

@interface YYMDownloadViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, copy) NSString *path;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation YYMDownloadViewController

- (void)viewWillAppear:(BOOL)animated{
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *createPath = [NSString stringWithFormat:@"%@/Image", pathDocuments];
    _path = createPath;
    _dataArray = [fileManager directoryContentsAtPath:createPath];
    
    [_tableView reloadData];
    
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _tableView = [[UITableView alloc] initWithFrame:CURRENTSCEEN style:UITableViewStyleGrouped];
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [self.view addSubview:_tableView];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIndentifier = @"cells";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    
    NSString *str = [_dataArray objectAtIndex:indexPath.section];
    
    cell.textLabel.text = str;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *str = [_dataArray objectAtIndex:indexPath.section];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", _path, str];
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSString *text in _dataArray) {
        
        XJCVideoModel *model = [[XJCVideoModel alloc] init];
        model.title = text;
        model.playUrl = [NSString stringWithFormat:@"%@/%@", _path, text];
        
        [array addObject:model];
    }
    
    XJCVideoPlayViewController *player = [[XJCVideoPlayViewController alloc] init];
    player.url = [NSURL fileURLWithPath:filePath];
    player.videoModelArray = array;
    [self presentViewController:player animated:YES completion:nil];
}

@end
